package com.dex4d.ui.mine.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.Toast;

import com.dex4d.R;
import com.dex4d.constants.IConstants;
import com.dex4d.core.AppToolBarBaseActivity;
import com.dex4d.core.http.DefaultTransformer;
import com.dex4d.core.http.JsonApiWrapper;
import com.dex4d.core.subscribers.ProgressSubscriber;
import com.dex4d.model.HttpResult;
import com.dex4d.model.RequestParam;
import com.dex4d.model.User;
import com.dex4d.ui.main.activity.TradeConfirmActivity;
import com.dex4d.ui.main.model.Dex4dTrade;
import com.dex4d.ui.main.model.TradeResult;
import com.dex4d.utils.Commons;

import org.web3j.utils.Convert;
import org.web3j.utils.Numeric;

import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.Collections;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by chengyuchun on 2018/11/7.
 */
public class ReferralAliasActivity extends AppToolBarBaseActivity {

    @BindView(R.id.et_referral_alias)
    EditText et_referral_alias;

    BigInteger mGasPrice;
    @Override
    protected void initToolbar() {
        showTitle(getString(R.string.referral_address));
        showBackView();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_referral_alias;
    }

    @Override
    protected void initVariables() {

    }

    @Override
    protected void loadData() {
        initGasPrice();
    }

    private void initGasPrice(){
        final RequestParam gasParam = new RequestParam();
        gasParam.setId(1);
        gasParam.setJsonrpc(IConstants.JSON_RPC_VERSION);
        gasParam.setMethod(IConstants.CONTRACTSERVICE_GASPRICE);
        gasParam.setParams(Collections.singletonList(User.getInstance().getAddress()));

        //gas price
        JsonApiWrapper
                .serviceApi()
                .requestByParam(gasParam)
                .compose(new DefaultTransformer<HttpResult<String>>())  //取网络数据这个函数不能少，这是线程切换
                .subscribe(new ProgressSubscriber<HttpResult<String>>(this, false) {
                    @Override
                    public void onNext(HttpResult<String> result) {
                        //服务器传过来的 GasPrice 是十进制
                        mGasPrice =  new BigInteger(result.getResult());
                    }
                });
    }

    private String calculateGasFee(int limitFlag){
        if(mGasPrice == null)
            return "0.0";

        BigInteger gasLimit = Numeric.toBigInt(Dex4dTrade.getHexGasLimit(limitFlag));
        return Convert.fromWei(mGasPrice.multiply(gasLimit).toString(), Convert.Unit.ETHER).setScale(6, RoundingMode.CEILING).toString();
    }

    private void verifyAlias(){
        String alias = et_referral_alias.getText().toString();
        if(TextUtils.isEmpty(alias)){
            Toast.makeText(this,getString(R.string.input_referral_alias),Toast.LENGTH_SHORT).show();
        }else if(!isAlphabet(alias.charAt(0))){
            Toast.makeText(this,getString(R.string.illegal_referral_alias),Toast.LENGTH_SHORT).show();
        }else {
            //调接口检查
            final RequestParam requestParam = new RequestParam();
            requestParam.setId(0);
            requestParam.setJsonrpc(IConstants.JSON_RPC_VERSION);
            requestParam.setMethod(IConstants.CONTRACTSERVICE_CHECKNAME);
            requestParam.setParams(Collections.singletonList(alias));

            JsonApiWrapper
                    .serviceApi()
                    .checkName(requestParam)
                    .compose(new DefaultTransformer<HttpResult<Boolean>>())  //取网络数据这个函数不能少，这是线程切换
                    .subscribe(new ProgressSubscriber<HttpResult<Boolean>>(this, true) {
                        @Override
                        public void onNext(HttpResult<Boolean> result) {
                            if(result.getResult()){
                                Bundle bundle = new Bundle();
                                bundle.putInt(Commons.BUNDLE_KEYS.TRADE_TYPE,TradeResult.FLAG_BUY_REFERRAL);
                                bundle.putString(Commons.BUNDLE_KEYS.COIN_AMOUNT,"0.500000");
                                bundle.putString(Commons.BUNDLE_KEYS.REFERRAL_ALIAS,et_referral_alias.getText().toString());
                                bundle.putString(Commons.BUNDLE_KEYS.GAS_CONSUMPTION,calculateGasFee(TradeResult.FLAG_BUY_REFERRAL));
                                openActivity(TradeConfirmActivity.class,bundle);
                            }else {
                                Toast.makeText(ReferralAliasActivity.this,getString(R.string.referral_alias_exists),Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
        }
    }

    //是否字母
    private boolean isAlphabet(char c){
        if((c>=97 && c<=122) || (c>=65 && c<=90)){
            return true;
        }else {
            return false;
        }
    }

    @OnClick(R.id.btn_confirm)
    public void onViewClick(){
        verifyAlias();
    }
}
